//
//  PhoneLoginViewController.m
//  SoundPill
//
//  Created by 温冬 on 15/5/1.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "PhoneLoginViewController.h"
#import "AFNetworking.h"
#import "ResetPasswordViewController.h"
#import "AppDelegate.h"
#import "JCAlertView.h"
@interface PhoneLoginViewController ()
@property (strong, nonatomic) NSUserDefaults *userDefaults;
@end

@implementation PhoneLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.userDefaults = [NSUserDefaults standardUserDefaults];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.login = [[Login alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [self.view addSubview:self.login];
    self.login.telNumber.field.delegate = self;
    self.login.password.field.delegate = self;
    [self.login.close addTarget:self action:@selector(loginClose:) forControlEvents:UIControlEventTouchUpInside];
    [self.login.certain addTarget:self action:@selector(loginCertain:) forControlEvents:UIControlEventTouchUpInside];
    [self.login.forget addTarget:self action:@selector(forgetButton:) forControlEvents:UIControlEventTouchUpInside];
    _login.telNumber.field.text = [_userDefaults valueForKey:@"telNumber"];
}

- (void)loginClose:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 登录
- (void)loginCertain:(UIButton *)button
{
    NSString *phoneRegex = @"^((177)|(13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    BOOL isUser = [phoneTest evaluateWithObject:self.login.telNumber.field.text];
    if (isUser == NO){
        UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
        customView.backgroundColor = [UIColor whiteColor];
        customView.text = @"手机号格式不正确";
        customView.textAlignment = NSTextAlignmentCenter;
        customView.layer.borderColor = [[UIColor blackColor] CGColor];
        customView.layer.borderWidth = 2;
        JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
        [_alert show];
        [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"手机号格式不正确" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
//        [alertView show];
//        [self performSelector:@selector(dismissAlert:) withObject:alertView afterDelay:1.5];
    }else if (self.login.password.field.text.length < 6){
        UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
        customView.backgroundColor = [UIColor whiteColor];
        customView.text = @"密码错误";
        customView.textAlignment = NSTextAlignmentCenter;
        customView.layer.borderColor = [[UIColor blackColor] CGColor];
        customView.layer.borderWidth = 2;
        JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
        [_alert show];
        [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
    }else{
        [self upLoading];
    }
}

- (void)dismissAlert:(UIAlertView *)alertView
{
    if (alertView) {
        [alertView dismissWithClickedButtonIndex:[alertView cancelButtonIndex] animated:YES];
    }
}

- (void)forgetButton:(UIButton *)button
{
    NSString *phoneRegex = @"^((177)|(13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    BOOL isUser = [phoneTest evaluateWithObject:self.login.telNumber.field.text];
    if (isUser == YES)
    {
        ResetPasswordViewController *resetVC = [[ResetPasswordViewController alloc] init];
        [self presentViewController:resetVC animated:YES completion:nil];
        resetVC.reset.telNumber = self.login.telNumber.field.text;
        [JCAlertView showOneButtonWithTitle:@"提示" Message:@"我们将发送验证码到你的手机，请注意查收" ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
            
        }];
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"我们将发送验证码到你的手机，请注意查收" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
//        [alertView show];
//        [self performSelector:@selector(dismissAlert:) withObject:alertView afterDelay:1.5];
        [self requsetSecurityCode];
    }else{
        UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
        customView.backgroundColor = [UIColor whiteColor];
        customView.text = @"手机号格式不正确";
        customView.textAlignment = NSTextAlignmentCenter;
        customView.layer.borderColor = [[UIColor blackColor] CGColor];
        customView.layer.borderWidth = 2;
        JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
        [_alert show];
        [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"手机号格式不正确" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
//        [self performSelector:@selector(dismissAlert:) withObject:alertView afterDelay:1.5];
//        [alertView show];
    }
}

#pragma mark - 向服务器上传数据
- (void)upLoading
{
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/login"];
    NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:self.login.telNumber.field.text, @"mobile", self.login.password.field.text, @"password", [AppDelegate shareDelegate].deviceToken, @"deviceToken", nil];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    [manager POST:url parameters:data progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [netWorkManager stopMonitoring];
        NSDictionary *data = responseObject;
        //将数据(token和uid)保存到NSUserDefaults
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString *token = [NSString stringWithFormat:@"%@",[data objectForKey:@"token"]];
        NSString *uid = [NSString stringWithFormat:@"%@",[data objectForKey:@"uid"]];
        [user setObject:token forKey:@"token"];
        [user setObject:uid forKey:@"uid"];
        [_userDefaults setValue:_login.telNumber.field.text forKey:@"telNumber"];
        //知道进入广场页面
        CATransition *transition = [CATransition animation];
        transition.duration = 0.8f;
        transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        transition.type = kCATransitionPush;
        transition.subtype = kCATransitionFromTop;
        transition.delegate = self;
        [self.view.superview.layer addAnimation:transition forKey:nil];
        [self.view removeFromSuperview];
        [[AppDelegate shareDelegate] chooseTabBarController];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [self requestUser:uid];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
        customView.backgroundColor = [UIColor whiteColor];
        customView.text = @"手机号或密码错误";
        customView.textAlignment = NSTextAlignmentCenter;
        customView.layer.borderColor = [[UIColor blackColor] CGColor];
        customView.layer.borderWidth = 2;
        JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
        [_alert show];
        [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
    }];
    
}


#pragma mark - 请求云片发送验证码
- (void)requsetSecurityCode
{
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/sendsms?mobile=%@&type=reset",self.login.telNumber.field.text];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    [manager POST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [netWorkManager stopMonitoring];
        
        //        NSLog(@"云片系统已将验证码发送到您的手机，请注意查收");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

#pragma mark - 点击完成按钮 登录
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSString *phoneRegex = @"^((177)|(13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    BOOL isUser = [phoneTest evaluateWithObject:self.login.telNumber.field.text];
    if (isUser == NO){
        UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
        customView.backgroundColor = [UIColor whiteColor];
        customView.text = @"手机号格式不正确";
        customView.textAlignment = NSTextAlignmentCenter;
        customView.layer.borderColor = [[UIColor blackColor] CGColor];
        customView.layer.borderWidth = 2;
        JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
        [_alert show];
        [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"手机号格式不正确" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
//        [alertView show];
//        [self performSelector:@selector(dismissAlert:) withObject:alertView afterDelay:1.5];
    }else if (self.login.password.field.text.length < 6){
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"密码位数不正确,至少6位" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
//        [alertView show];
//        [self performSelector:@selector(dismissAlert:) withObject:alertView afterDelay:1.5];
        UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
        customView.backgroundColor = [UIColor whiteColor];
        customView.text = @"密码位数不正确,至少6位";
        customView.textAlignment = NSTextAlignmentCenter;
        customView.layer.borderColor = [[UIColor blackColor] CGColor];
        customView.layer.borderWidth = 2;
        JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
        [_alert show];
        [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
    }else{
        [self upLoading];
    }
    return YES;
}

#pragma mark - 回收键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.login.telNumber.field resignFirstResponder];
    [self.login.password.field resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)requestUser:(NSString *)uid
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSDictionary *data = [[NSDictionary alloc]init];
    NSString *str =[NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/show",uid];
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    [manager GET:str parameters:data progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict= responseObject;
        NSMutableDictionary *datadic = [[NSMutableDictionary alloc] initWithDictionary:[dict objectForKey:@"data"]];
        if ([[datadic valueForKey:@"introduce"] isKindOfClass:[NSNull class]] || [datadic valueForKey:@"introduce"] == nil) {
            [datadic setValue:@"这家伙来自外星，还没学会地球语言" forKey:@"introduce"];
        }
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:datadic forKey:@"myDictionary"];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
